/**
 * Copyright (c)2002-2006 by OpenSymphony
 * All rights reserved.
 */
package com.dev.security.manager.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import com.dev.security.login.beans.LoginData;
import com.dev.security.login.service.LoginManager;
import com.dev.security.login.util.LoginConstants;

/**
 * @author 潜行的青衣
 * @see
 */
@Controller
@RequestMapping("/login/")
public class LoginController {

	@Autowired
	private LoginManager loginManger;
	
	@RequestMapping("page")
	public String page(HttpServletRequest request) {
		request.setAttribute("account_field", this.loginManger.getAccountFieldName());
		request.setAttribute("password_field", this.loginManger.getPasswordFieldName());
		request.setAttribute("isCookie_field", this.loginManger.getIsCookieFieldName());
		return "login/page";
	}
	
	@RequestMapping("submit")
	public String submit(HttpServletRequest request, HttpServletResponse response) {
		LoginData data = this.loginManger.login(request, response);
		if(data.getCode() == LoginConstants.LOGIN_TRANSIT) {
			return "redirect:/manager/index";
		} else {
			Map<Integer, String> errors = new HashMap<Integer, String>();
			
			request.setAttribute("errors", errors);
			request.setAttribute("error_code", data.getCode());
			
			RequestContext requestContext = new RequestContext(request);
			errors.put(LoginConstants.LOGIN_INVALID, requestContext.getMessage("login.error.invalid"));
			errors.put(LoginConstants.LOGIN_PASSWORD, requestContext.getMessage("login.error.password"));
			return page(request);
		}
	}
	
	@RequestMapping("logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		this.loginManger.logout(request, response);
		return this.page(request);
	}
	
}
